//////////////////////////////////////////////////////////////////////////

#ifndef _NEWRESEARCHDIALOG_H_
#include "newresearchdialog.h"
#endif

//////////////////////////////////////////////////////////////////////////

#include "ui_newresearchdialog.h"

#ifndef _MAINWINDOW_H_
#include "mainwindow.h"
#endif

#include <QTimer>
#include <QMessageBox>


//////////////////////////////////////////////////////////////////////////


NewResearchDialog::NewResearchDialog( QWidget* _parent )
: Dialog(_parent),
  m_Started(false),
  m_ui(new Ui::NewResearchDialog)
{
    m_ui->setupUi(this);
    m_ui->m_DateEdit->setDate(QDate::currentDate());

    connect( m_ui->m_StartButton, SIGNAL(clicked()), this, SLOT(Start()) );
    connect( m_ui->m_StopButton, SIGNAL(clicked()), this, SLOT(Stop()) );
}


//////////////////////////////////////////////////////////////////////////


NewResearchDialog::~NewResearchDialog()
{
    delete m_ui;
}


//////////////////////////////////////////////////////////////////////////


void NewResearchDialog::Start()
{
    try
    {
        if (!m_Started)
        {
            m_Started = true;
            m_Device.Start();

            int seconds = m_ui->m_AutostopBox->value();
            if (seconds)
                QTimer::singleShot( seconds * 1000, this, SLOT(Stop()) );
        }
    }
    catch (...)
    {
        // Cannot open COM port
        QMessageBox box(QMessageBox::Warning, tr("Error"),
            tr("Cannot open COM port."),
            QMessageBox::Ok, this);

        box.exec();
    }
}


//////////////////////////////////////////////////////////////////////////


void NewResearchDialog::Stop()
{
    if (m_Started)
    {
        m_Started = false;
        m_Device.Stop();
    }
}


//////////////////////////////////////////////////////////////////////////


void NewResearchDialog::accept()
{
    try
    {
        Research* research = new Research(m_ui->m_DateEdit->text());
        m_Device.ReadData(*research);
        research->Calculate();
    
        GetMainWindow()->GetCurrPatient().SetCurrentResearch(research);
        GetMainWindow()->GetDatabase().SaveCurrentResearch( GetMainWindow()->GetCurrPatient() );

        GetMainWindow()->ShowCurrentResearch();
    }
    catch (...)
    {
        // Data error
        QMessageBox box(QMessageBox::Warning, tr("Error"),
            tr("Cannot read data."),
            QMessageBox::Ok, this);
        
        box.exec();
    }
}


//////////////////////////////////////////////////////////////////////////
